package com.jackrain.nea.omslocal.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.omslocal.conf.LoadCloumnsConfig;
import com.jackrain.nea.omslocal.util.SplitArrUtil;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Discription: 奇门创建发货单接口,
 * Created with IntelliJ IDEA.
 * @Author cs
 * @Date 2017/12/7 17:27
 */
@Component
@Slf4j
public class QiMenWmsDeliceryOrderCreatService {

    @Autowired
    private SendMqServies sendMq;
    @Autowired
    private LoadCloumnsConfig loadCloumnsConfig;
    @Autowired
    private PropertiesConf pconf;
    @Autowired
    private LocalLogService localLogService;
    @Autowired
    private SplitArrUtil splitArrUtil;

    /**
     * 奇门创建发货单 发送
     */
    public void deliceryOrderCreatStart() {
        // 获取自身 bean
        QiMenWmsDeliceryOrderCreatService qmdocs = ApplicationContextHandle.getBean(QiMenWmsDeliceryOrderCreatService.class);
        // 正常创建发货单
        qmdocs.psoDeliceryOrderSend();

    }

    /**
     * 奇门创建发货单 发送
     */
    public void deliceryOrderCreatSendAgainStart() {
        // 获取自身 bean
        QiMenWmsDeliceryOrderCreatService qmdocs = ApplicationContextHandle.getBean(QiMenWmsDeliceryOrderCreatService.class);
        // 失败重复发送
        qmdocs.deliceryOrderCreatSendAgain();
    }

    /**
     * 查询创建发货单表
     *
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void psoDeliceryOrderSend() {

        try {
            // 查询上限
            int rownums = pconf.getPropertyInt("ons.deliceryNum");
            // 查询回流表数据 Read_status = 0 未读取状态数据   =9 已发送,为回执    =1 成功
            String countSql = "select * from t_omserpwmsorder where Read_status = 0 and  rownum <= " + rownums + " order by " +
                    "id for update skip locked";


            JSONArray jsonArr = QueryEngine.getInstance().doQueryObjectArray(countSql);

            if (jsonArr == null || jsonArr.isEmpty()) {
                // 创建发货单没有需要同步的数据
                log.debug("posdeliceryOrder jsonArr is null");
                return;
            }
            String topic = pconf.getProperty("ons.deliceryordercreatTopic", "TAOBAO_QIMEN_DELICERYORDER_CREATE");
            String tag = pconf.getProperty("ons.comp");
            int sendNum = pconf.getPropertyInt("ons.deliceryssendNum");

            // 不为空则查询子表关联数据
            ValueHolder valueHolder = queryProduct(jsonArr);
            JSONArray resultArr = JSONArray.parseArray(valueHolder.get("resultArr").toString());

            if (resultArr.size() > sendNum) {
                JSONArray msgArr = splitArrUtil.splitArr(resultArr, sendNum);

                for (int i = 0; i < msgArr.size(); i++) {
                    String dataArr = (String) msgArr.get(i);
                    // 构造数据结构
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("data", dataArr);
                    jsonObject.put("tag", tag);
                    sendMq.sendMqinfoObj(jsonObject, topic, tag);
                }
                return;
            }

            // 有需要回流的数据 将查询到的数据以消息形式发送
            // 构造数据结构
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", resultArr.toJSONString());
            jsonObject.put("tag", tag);
            sendMq.sendMqinfoObj(jsonObject, topic, tag);
            // 修改数据的同步状态为 已发送 9
            changeStatus(JSONArray.parseArray(valueHolder.get("idArr").toString()), 1);

        } catch (Exception e) {
            //  同步发货状态出现异常
            log.error("创建发货单发送失败 ： " + e.getCause() + "========  : " + e.getMessage());

        }

    }

    /**
     * 查询创建发货单表, 失败重发
     *
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void deliceryOrderCreatSendAgain() {

        try {
            // 查询上限
            int rownums = pconf.getPropertyInt("ons.deliceryNum");
            // 查询创建发货单表,where Read_status = 9 , 为已发送一次的数据 大于五分钟小于十分钟 的数据重发 ,超过十分钟的,默认为发生异常错误,需要手动解决
            String countSql = "select * from t_omserpwmsorder where Read_status = 1 and creationdate <= sysdate - 5/1440 and rownum <= " + rownums + " order by " +
                    "id for update skip locked";
            JSONArray jsonArr = QueryEngine.getInstance().doQueryObjectArray(countSql);

            if (jsonArr == null || jsonArr.isEmpty()) {
                // 没有同步的数据
                log.debug("deliceryOrderCreat----没有需要重复发送的数据");
                return;
            }
            String topic = pconf.getProperty("ons.deliceryordercreatTopic", "TAOBAO_QIMEN_DELICERYORDER_CREATE");
            String tag = pconf.getProperty("ons.comp");
            int sendNum = pconf.getPropertyInt("ons.deliceryssendNum");

            // 有需要重复发送的数据 将查询到的数据以消息形式发送 , 查询关联子表数据 , 构造数据形式
            ValueHolder valueHolder = queryProduct(jsonArr);
            JSONArray resultArr = JSONArray.parseArray(valueHolder.get("resultArr").toString());
            if (resultArr.size() > sendNum) {
                JSONArray msgArr = splitArrUtil.splitArr(resultArr, sendNum);

                for (int i = 0; i < msgArr.size(); i++) {
                    String dataArr = (String) msgArr.get(i);
                    // 构造数据结构
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("data", dataArr);
                    jsonObject.put("tag", tag);
                    sendMq.sendMqinfoObj(jsonObject, topic, tag);
                }
                return;
            }

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", resultArr.toJSONString());
            jsonObject.put("tag", tag);
            sendMq.sendMqinfoObj(jsonObject, topic, tag);

            // 重复发送的数据状态不再变更, 等待人工处理
            changeStatus(JSONArray.parseArray(valueHolder.get("idArr").toString()), 2);
        } catch (Exception e) {
            //  同步发货状态出现异常
            log.error("同步创建发货单异常");
        }

    }

    /**
     * 查询关联子表数据
     *
     * @param jsonArray
     * @return
     */
    private ValueHolder queryProduct(JSONArray jsonArray) {

        ValueHolder vh = new ValueHolder();
        JSONArray resultArr = new JSONArray();
        JSONArray idArr = new JSONArray();

        try {
            String querySql = "select * from t_omserpwmsproduct where omserpwmsorderid = ?";
            // 循环遍历
            for (Object obj : jsonArray) {

                JSONObject idObj = new JSONObject();
                JSONObject tempObj = JSONObject.parseObject(obj.toString(), Feature.OrderedField);
                int id = tempObj.getInteger("ID");
                // 将 id 封装, 修改日志
                idObj.put("id", id);
                idArr.add(idObj);
                JSONArray productArr = QueryEngine.getInstance().doQueryObjectArray(querySql, new Object[]{id});
                if (null == productArr || productArr.isEmpty()) {
                    //没有子表数据,避免 nullpoint
                    productArr = new JSONArray();
                }
                tempObj.put("products", productArr.toString());
                resultArr.add(tempObj);
            }

        } catch (Exception e) {
            // 查询数据发生异常,处理再抛出
            log.error(e.getMessage());
            throw e;
        }
        vh.put("idArr", idArr);
        vh.put("resultArr", resultArr);
        return vh;
    }

    private void changeStatus(JSONArray paramArr, int type) {

        // 状态为 3 的是 已失败重发送 ， 2 是成功
        String sql = "update t_omserpwmsorder set READ_STATUS = 1 where id=?";
        String sqlAgain = "update t_omserpwmsorder set READ_STATUS = 3 where id=?";

        try {
            if (type == 1) {
                // 第一次发送修改状态
                QueryEngine.getInstance().executeBatchUpdate(sql, paramArr);
            } else if (type == 2) {
                // 失败重发修改状态
                QueryEngine.getInstance().executeBatchUpdate(sqlAgain, paramArr);

            }
        } catch (Exception e) {
            // 修改发货单创建数据发生异常
            log.error("修改发货单创建数据发生异常 : " + e.getMessage());
            throw e;
        }

    }

}
